/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package kale.ui.shatter.adapter;

import kale.ui.shatter.Shatter;
import kale.ui.shatter.ShatterManager;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.PageSliderProvider;

/**
 * ShatterPagerAdapter
 *
 * @since 2021-05-20
 */
public abstract class ShatterPagerAdapter extends PageSliderProvider {
    private static final int ITEM_TYPE = -1;

    private final ShatterManager mManager;

    /**
     * ShatterPagerAdapter
     *
     * @param manager
     */
    public ShatterPagerAdapter(ShatterManager manager) {
        super();
        mManager = manager;
    }

    @Override
    public boolean isPageMatchToObject(Component component, Object o) {
        return component == ((Shatter) o).getRootView();
    }

    @Override
    public Component createPageInContainer(ComponentContainer componentContainer, int position) {
        Object type = getItemType(position);
        Shatter shatter = createItem(type);
        mManager.add(componentContainer, shatter);

        // 通过item得到将要被add到viewpager中的view
        Component view = shatter.getRootView();
        view.setTag(type); // set tag

        if (view.getComponentParent() != null) {
            view.getComponentParent().removeComponent(view);
        }
        componentContainer.addComponent(view);
        afterInstantiateItem(shatter, position);
        return view;
    }

    /**
     * 实例item后回调
     *
     * @param item
     * @param position
     */
    protected void afterInstantiateItem(Shatter item, int position) {
    }

    @Override
    public void destroyPageFromContainer(ComponentContainer container, int position, Object object) {
        container.removeComponent((Component) object);
    }

    @Override
    public void onUpdateFinished(ComponentContainer componentContainer) {
        super.onUpdateFinished(componentContainer);
    }

    @Override
    public void startUpdate(ComponentContainer container) {
        super.startUpdate(container);
    }

    /**
     * getItemType
     *
     * @param position
     * @return type
     */
    public Object getItemType(int position) {
        return ITEM_TYPE; // default
    }

    /**
     * 当没办法从缓存中得到item的时候才会调用此方法
     *
     * @param type
     * @return Shatter
     */
    public abstract Shatter createItem(Object type);
}
